import {Component, OnInit, ViewChild} from '@angular/core';
import {HttpService} from "../../../lib/service/http.service";
import {adSystemApiUrl, tuikeSystemUrl} from "../../../../config/api";
import {ModalDirective} from "ngx-bootstrap";
import {Headers, RequestOptions} from "@angular/http";
import {ActivatedRoute, Router} from "@angular/router";

@Component({
  selector: 'app-push',
  templateUrl: './push.component.html',
  styleUrls: ['./push.component.scss']
})
export class PushComponent implements OnInit {

  type: string;
  message: string;
  isShow = true;
  totalItems: number;
  currentPage: number = 1;
  itemsPerPage: number = 20;
  _isSpinning = false;
  error = false;
  addStatus = false;
  pushList = [];
  status = {
    '1': '新增',
    '2': '等待推送',
    '3': '已推送',
    '4': '放弃推送',
    '5': '发送循环达上限报错',
    '6': '失败的重新发送',
    '-1': '推送失败',
    '-2': '有问题,看日志'
  };
  pushId = null;
  editId = null;

  constructor(private httpService: HttpService, private router: Router, private route: ActivatedRoute) {
  }

  @ViewChild('confirmModal') public confirmModal: ModalDirective;

  ngOnInit() {
    this.route.snapshot.queryParams['page'] ? this.currentPage = +this.route.snapshot.queryParams['page'] : this.currentPage = 1;
    this.getPushList();
  }

  pageChange() {
    this.getPushList();
  }

  getPushList() {
    this._isSpinning = true;
    const url = `${tuikeSystemUrl}/api/v1/admin/wechat_message_send/send_list?page=${this.currentPage}&pageSize=${this.itemsPerPage}`;
    this.httpService.httpGetAuth(url).subscribe(res => {
      if (res.code === 200) {
        this.pushList = res.data.data;
        this.totalItems = res.data.total;
        this._isSpinning = false;
      }
    })
  }

  goEdit(id, activityId, info?) {
    let params = null;
    console.log(info);
    info != true ? params = {
        id: activityId,
        pushId: id,
        page:this.currentPage
      } :
      params = {
        id: activityId,
        pushId: id,
        readonly: true,
        page:this.currentPage
      };
    this.router.navigate(['tuike/discovery/add'], {
      queryParams: params
    })
  }

  pageChanged(event: any, page?): void {
    window.scrollTo(0, 0);
    this.currentPage = event.page;
    this.getPushList();
  }

  showConfirmModal(id) {
    this.editId = id;
    this.confirmModal.show();
  }

  deletePush() {
    const url = `${tuikeSystemUrl}/api/v1/admin/wechat_message_send/cancel_message`;
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const body = JSON.stringify({'id': this.editId});
    this.httpService.httpPostAuth(url, body, options).subscribe(res => {
      console.log(res);
    })
  }
}
